package com.zhang.flink.example;

import com.zhang.flink.bean.IntegerResult;
import com.zhang.flink.example.source.IntegerSource;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title: reduce同时求最大值、最小值、总和、总个数、平均数
 * @author: zhang
 * @date: 2022/2/11 19:43
 */
public class ProcessWithMaxAndMin {
    public static void main(String[] args) throws Exception {
        // todo 获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                // 因为要求最大值和最小值，所以应该对全局进行处理，这里keyBy到同一个逻辑分区
                .keyBy(r -> 1)
                .process(new KeyedProcessFunction<Integer, Integer, IntegerResult>() {
                    private ValueState<IntegerResult> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        valueState = getRuntimeContext().getState(
                                new ValueStateDescriptor<IntegerResult>(
                                        "integer-state",
                                        Types.POJO(IntegerResult.class)
                                )
                        );
                    }

                    @Override
                    public void processElement(Integer value, KeyedProcessFunction<Integer, Integer, IntegerResult>.Context ctx, Collector<IntegerResult> out) throws Exception {
                        if (valueState.value() == null) {
                            valueState.update(new IntegerResult(
                                    value,
                                    value,
                                    value,
                                    1,
                                    value
                            ));
                        } else {
                            IntegerResult tmp = valueState.value();
                            valueState.update(new IntegerResult(
                                    Math.max(tmp.max, value),
                                    Math.min(tmp.min, value),
                                    tmp.sum + value,
                                    tmp.count + 1,
                                    (tmp.sum + value) / (tmp.count + 1)
                            ));
                        }
                        out.collect(valueState.value());
                    }
                })
                .print();

        env.execute();
    }
}
